import os
import requests
import json
import yaml
from os import path
import json
import re
from templement import *
import copy
class AutoUpdateMqtt:
    def __init__(self) -> None:
        # self.sourcefile = path.join("configuration.yaml")
        # self.targetfile = path.join("mqtt.json")
        # 当前目录
        self.sourcefile = path.join( path.dirname(__file__),"configuration.yaml")
        self.targetfile = path.join( path.dirname(__file__),"mqtttemp.json")
        self.mappings = []
        self._rpc = {"serverSideRpc": []}
        self.names = []
        self.load_config()
        pass

    def load_config(self):
        with open(self.sourcefile, "r", encoding='utf-8') as f:
            self.config = yaml.safe_load(f)
        with open(self.targetfile, "r", encoding='utf-8') as f:
            self.mqtt = json.load(f)

    def creat_temprature_mapping(self):
        self._temprature = {}
        if self.config.get("devices") is None:
            return
        for temprature in self.config["devices"].values():
            if temprature.get("friendly_name").split("/")[0] not in self._temprature:
                self._temprature[temprature.get("friendly_name").split("/")[0]] = []
            self._temprature[temprature.get("friendly_name").split("/")[0]].append(temprature.get("friendly_name"))
        temprature_template = ZIGBEE2MQTT_TEMPERATURE_MAPPING
        temprature_template["converter"]["deviceTypeJsonExpression"] = TEMPERATURE_TYPE
        temprature_template["converter"]["deviceLabelJsonExpression"] = SENSOR_LABEL
        for temprature in self._temprature:
            if temprature == "单路开关" or temprature == "双路开关" or temprature == "三路开关":
                # 深拷贝取模板
                temprature_double_mapping = copy.deepcopy(temprature_template)
                temprature_double_mapping["topicFilter"] = temprature_template["topicFilter"] + temprature + "/+"
                temprature_double_mapping["converter"]["timeseries"][0]["value"] = "${" + TEMPERATURE + "}"
                temprature_double_mapping["converter"]["deviceNameTopicExpression"] = TEMPERATURE_GET
                self.mappings.append(temprature_double_mapping)
            else:
                pass

    def creat_switch_mapping(self):
        self._switch = {}
        if self.config.get("devices") == None:
            return
        for switch in self.config["devices"].values():
            if type(switch) != dict:
                continue
            if switch.get("friendly_name").split("/")[0] not in self._switch:
                self._switch[switch.get("friendly_name").split("/")[0]] = []
            self._switch[switch.get("friendly_name").split("/")[0]].append(switch.get("friendly_name"))
        switch_template = ZIGBEE2MQTT_SWITCH_MAPPING
        switch_template["converter"]["deviceTypeJsonExpression"] = LIGHTING_SWITCH
        switch_template["converter"]["deviceLabelJsonExpression"] = ENERGY_CONSUMING_EQUIPMENT
        switch_mappings = []
        for switch in self._switch:
            if switch == "单路开关":
                # 深拷贝取模板
                switch_double_mapping_left = copy.deepcopy(switch_template)
                switch_double_mapping_left["topicFilter"] = switch_template["topicFilter"] + switch + "/+"
                switch_double_mapping_left["converter"]["timeseries"][0]["value"] = "${" + STATE + "}"
                switch_double_mapping_left["converter"]["deviceNameTopicExpression"] = SWITCHLEFT
                switch_mappings.append(switch_double_mapping_left)

            elif switch == "双路开关":
                # 取新模板
                switch_double_mapping_left = copy.deepcopy(switch_template)
                switch_double_mapping_left["topicFilter"] = switch_template["topicFilter"] + switch + "/+"
                switch_double_mapping_left["converter"]["timeseries"][0]["value"] = "${" + STATE_LEFT + "}"
                switch_double_mapping_left["converter"]["deviceNameTopicExpression"] = SWITCHLEFT
                switch_mappings.append(switch_double_mapping_left)
                switch_double_mapping_right = copy.deepcopy(switch_template)
                switch_double_mapping_right["topicFilter"] = switch_template["topicFilter"] + switch + "/+"
                switch_double_mapping_right["converter"]["timeseries"][0]["value"] = "${" + STATE_RIGHT + "}"
                switch_double_mapping_right["converter"]["deviceNameTopicExpression"] = SWITCHRIGHT
                switch_mappings.append(switch_double_mapping_right)
            elif switch == "三路开关":
                # 取新模板
                switch_triple_mapping_left = copy.deepcopy(switch_template)
                switch_triple_mapping_left["topicFilter"] = switch_template["topicFilter"] + switch + "/+"
                switch_triple_mapping_left["converter"]["timeseries"][0]["value"] = "${" + STATE_LEFT + "}"
                switch_triple_mapping_left["converter"]["deviceNameTopicExpression"] = SWITCHLEFT
                switch_mappings.append(switch_triple_mapping_left)
                switch_triple_mapping_middle = copy.deepcopy(switch_template)
                switch_triple_mapping_middle["topicFilter"] = switch_template["topicFilter"] + switch + "/+"
                switch_triple_mapping_middle["converter"]["timeseries"][0]["value"] = "${" + STATE_CENTER + "}"
                switch_triple_mapping_middle["converter"]["deviceNameTopicExpression"] = SWITCHCENTER
                switch_mappings.append(switch_triple_mapping_middle)
                switch_triple_mapping_right = copy.deepcopy(switch_template)
                switch_triple_mapping_right["topicFilter"] = switch_template["topicFilter"] + switch + "/+"
                switch_triple_mapping_right["converter"]["timeseries"][0]["value"] = "${" + STATE_RIGHT + "}"
                switch_triple_mapping_right["converter"]["deviceNameTopicExpression"] = SWITCHRIGHT
                switch_mappings.append(switch_triple_mapping_right)
                pass
        self.mappings.extend(switch_mappings)
        #print(self.mappings)

    def creat_ir_aircondition_mapping(self):
        self.mappings.append(ZIGBEE2MQTT_IR_AIRCONDITION_MAPPING)

    def creat_aircondition_mapping(self):
        self.mappings.append(ZIGBEE2MQTT_AIRCONDITION_MAPPING)

    def creat_service_rpc(self,type):
        serverside_rpc_dict_template = ZIGBEE2MQTT_SERVERSIDE_RPC
        if type == "ir_serverside_rpc":
            ir_serverside_rpc_dict_template = IR_SENDER_SERVERSIDE_RPC
            # 空调红外码
            ir_func_list = [SET_STATE_OPEN, SET_STATE_CLOSE, SET_WINDSPEED_AUTO, SET_WINDSPEED_ONE, SET_WINDSPEED_TWO,
                            SET_WINDSPEED_THREE, SET_WINDSPEED_FOUR, SET_WINDSPEED_FIVE, SET_WINDSPEED_SIX,
                            SET_WINDSPEED_SEVEN, SET_MODE_AUTO, SET_MODE_COLD, SET_MODE_HOT, SET_MODE_DRY, SET_MODE_FAN,
                            SET_TEM_T17, SET_TEM_T18, SET_TEM_T19, SET_TEM_T20, SET_TEM_T21, SET_TEM_T22, SET_TEM_T23,
                            SET_TEM_T24, SET_TEM_T25, SET_TEM_T26, SET_TEM_T27, SET_TEM_T28, SET_TEM_T29, SET_TEM_T30]
            for ir_func in ir_func_list:
                ir_serverside_rpc_dict = copy.deepcopy(ir_serverside_rpc_dict_template)
                ir_serverside_rpc_dict["methodFilter"] = ir_func
                self._rpc["serverSideRpc"].append(ir_serverside_rpc_dict)
        elif type == "switchs_serverside_rpc":
            if self._switch is not None:
                for switch in self._switch:
                    if switch == "单路开关":
                        for switch_name in self._switch[switch]:
                            sig_serverside_rpc_dict = copy.deepcopy(serverside_rpc_dict_template)
                            sig_serverside_rpc_dict["deviceNameFilter"] = re.findall("(?<=%1\[)(.+?)(?=\]1%)", switch_name)[
                                0]
                            sig_serverside_rpc_dict["requestTopicExpression"] = sig_serverside_rpc_dict[
                                                                                    "requestTopicExpression"] + switch_name + "/set"
                            self._rpc["serverSideRpc"].append(sig_serverside_rpc_dict)
                    elif switch == "双路开关":
                        for switch_name in self._switch[switch]:
                            d1_serverside_rpc_dict = copy.deepcopy(serverside_rpc_dict_template)
                            # 正则表达式"(?<=%1)(.+?)(?=1%)"值
                            d1_serverside_rpc_dict["deviceNameFilter"] = re.findall("(?<=%1\[)(.+?)(?=\]1%)", switch_name)[
                                0]
                            d1_serverside_rpc_dict["requestTopicExpression"] = d1_serverside_rpc_dict[
                                                                                "requestTopicExpression"] + switch_name + "/set"
                            d1_serverside_rpc_dict["valueExpression"] = '{\"state_left\":${params.state}}'
                            self._rpc["serverSideRpc"].append(d1_serverside_rpc_dict)
                            d2_serverside_rpc_dict = copy.deepcopy(serverside_rpc_dict_template)
                            d2_serverside_rpc_dict["deviceNameFilter"] = re.findall("(?<=%2\[)(.+?)(?=\]2%)", switch_name)[
                                0]
                            d2_serverside_rpc_dict["requestTopicExpression"] = d2_serverside_rpc_dict[
                                                                                "requestTopicExpression"] + switch_name + "/set"
                            d2_serverside_rpc_dict["valueExpression"] = '{\"state_right\":${params.state}}'
                            self._rpc["serverSideRpc"].append(d2_serverside_rpc_dict)
                    elif switch == "三路开关":
                        for switch_name in self._switch[switch]:
                            d1_serverside_rpc_dict = copy.deepcopy(serverside_rpc_dict_template)
                            d1_serverside_rpc_dict["deviceNameFilter"] = re.findall("(?<=%1\[)(.+?)(?=\]1%)", switch_name)[
                                0]
                            d1_serverside_rpc_dict["requestTopicExpression"] = d1_serverside_rpc_dict[
                                                                                "requestTopicExpression"] + switch_name + "/set"
                            d1_serverside_rpc_dict["valueExpression"] = '{\"state_left\":${params.state}}'
                            self._rpc["serverSideRpc"].append(d1_serverside_rpc_dict)
                            d2_serverside_rpc_dict = copy.deepcopy(serverside_rpc_dict_template)
                            d2_serverside_rpc_dict["deviceNameFilter"] = re.findall("(?<=%2\[)(.+?)(?=\]2%)", switch_name)[
                                0]
                            d2_serverside_rpc_dict["requestTopicExpression"] = d2_serverside_rpc_dict[
                                                                                "requestTopicExpression"] + switch_name + "/set"
                            d2_serverside_rpc_dict["valueExpression"] = '{\"state_center\":${params.state}}'
                            self._rpc["serverSideRpc"].append(d2_serverside_rpc_dict)
                            d3_serverside_rpc_dict = copy.deepcopy(serverside_rpc_dict_template)
                            d3_serverside_rpc_dict["deviceNameFilter"] = re.findall("(?<=%3\[)(.+?)(?=\]3%)", switch_name)[
                                0]
                            d3_serverside_rpc_dict["requestTopicExpression"] = d3_serverside_rpc_dict[
                                                                                "requestTopicExpression"] + switch_name + "/set"
                            d3_serverside_rpc_dict["valueExpression"] = '{\"state_right\":${params.state}}'
                            self._rpc["serverSideRpc"].append(d3_serverside_rpc_dict)
                        pass
        elif type == "airc_serverside_rpc":
            for temp_dictionary in self._rpc["serverSideRpc"]:
                if AIRCONDITION_SERVERSIDE_RPC == temp_dictionary:
                    self._rpc["serverSideRpc"].remove(temp_dictionary)
            self._rpc["serverSideRpc"].append(AIRCONDITION_SERVERSIDE_RPC)


    def get_names(self):
        for devicename in self.config["devices"].values():
            if devicename.get("friendly_name").split("/")[0] == "空调设备":
                self.names.append(devicename.get("friendly_name").split("/")[1])
            if "开关" in devicename.get("friendly_name").split("/")[0]:
                if devicename.get("friendly_name").split("/")[0] == "单路开关":
                    self.names.append(re.findall("(?<=%1\[)(.+?)(?=\]1%)", devicename.get("friendly_name"))[0])
                elif devicename.get("friendly_name").split("/")[0] == "双路开关":
                    self.names.append(re.findall("(?<=%1\[)(.+?)(?=\]1%)", devicename.get("friendly_name"))[0])
                    self.names.append(re.findall("(?<=%2\[)(.+?)(?=\]2%)", devicename.get("friendly_name"))[0])
                elif devicename.get("friendly_name").split("/")[0] == "三路开关":
                    self.names.append(re.findall("(?<=%1\[)(.+?)(?=\]1%)", devicename.get("friendly_name"))[0])
                    self.names.append(re.findall("(?<=%2\[)(.+?)(?=\]2%)", devicename.get("friendly_name"))[0])
                    self.names.append(re.findall("(?<=%3\[)(.+?)(?=\]3%)", devicename.get("friendly_name"))[0])

        # 打开json文件并写入
        with open(path.join(path.dirname(__file__), "names.json"), "w", encoding='utf-8') as f:
            print(f"数据{self.names}  {f}")
            json.dump(self.names, f, indent=4, ensure_ascii=False)

    
    def start(self):
        self.creat_switch_mapping()
        self.creat_aircondition_mapping()
        #self.creat_ir_aircondition_mapping()
        # self.creat_temprature_mapping()
        self.creat_service_rpc("switchs_serverside_rpc")
        self.creat_service_rpc("airc_serverside_rpc")
        
        while len(self.mappings) > 0:
            element = self.mappings.pop(0)
            for my_dict in self.mqtt["mapping"]:
                if "topicFilter" in my_dict and my_dict["topicFilter"] == element["topicFilter"]:
                    # 如果存在，从列表中删除当前字典
                    self.mqtt["mapping"].remove(my_dict)
            self.mqtt["mapping"].append(element)

        #self.mqtt["serverSideRpc"] = self._rpc["serverSideRpc"]
        while len(self._rpc["serverSideRpc"]) > 0:
            element = self._rpc["serverSideRpc"].pop(0)
            for my_dict in self.mqtt["serverSideRpc"]:
                if my_dict == element:
                    self.mqtt["serverSideRpc"].remove(my_dict)
            self.mqtt["serverSideRpc"].append(element)
        # 规则打印
        # print(json.dumps(self.mqtt, indent=4, ensure_ascii=False))
        # 写入json
        # with open(path.join(path.dirname(__file__), "mqtt.json"), "w", encoding='utf-8') as f:
        #     json.dump(self.mqtt, f, indent=4, ensure_ascii=False)
        return self.mqtt

    def get_mqttjson(self,zigbee_config):
        #初始化self.mqtt
        self.load_config()
        self.config = zigbee_config
        #print(zigbee_config)
        self.start()
        return self.mqtt

# if __name__ == "__main__":
#     auto_update_mqtt = AutoUpdateMqtt()
#     auto_update_mqtt.start()
#     pass

# 获取设备属性和遥测值
base_telemetry_url = "http://218.201.94.143/api/plugins/telemetry/DEVICE/"

gwtoken = {
    "192.168.100.54": "l6jFrMoKRX8q4h73z5cE",
    "192.168.100.9": "hjnGBe0Y58vZhm5aC2Sj",
    "192.168.100.8": "y3YnfNDGTFVpMIODxSg9",
    "192.168.100.7": "xwyt2tv1AnRBDlhTdbIz",
    "192.168.100.6": "dbRv8TV3iclXtqyzCzWb",
    "192.168.100.5": "xUMkOBNux0XCsZmZDL1R",
    "192.168.100.14": "Qx0gqPNLU5vlCDkScwmH",
    "192.168.100.18": "fiJhcBMJgioMltUdZRNq",
    "192.168.100.20": "SKUPYmHo9fbnwMrHbkov",
    "192.168.100.19": "OalVaybWyzggjuuY1hi5",
    "192.168.100.21": "7OJ2SDxdLIV6ltUFAZZ4",
    "192.168.100.22": "VDQyme3l8lo5IThpuLlJ",
    "192.168.100.26": "tP8x99tWjUkXWOP7S1nY",
    "192.168.100.27": "lWRcGSfPnnn0cpUYeNlF",
    "192.168.100.29": "SH8hZpj7RPkonCvc4oww",
    "192.168.100.30": "MNuMQ3rMDo05rSY5hcOi",
    "192.168.100.28": "cCGUvwjbJSpEAGjbCnES",
    "192.168.100.33": "6yq9siQVRs4qXnhYiaeR",
    "192.168.100.35": "Z4dBjDXLHW9sxcGgBlq2",
    "192.168.100.31": "a4VvvtxYKRA5V5azwS58",
    "192.168.100.37": "JLAJvlRjGLComZpvgJro",
    "192.168.100.36": "Gw5gsHg5CvwZXawKXLB2",
    "192.168.100.39": "hwTZAiWEIpBWMfZH6per",
    "192.168.100.38": "LVfnOD6Adamnr1xSiKle",
    "192.168.100.40": "QIyoVBXuT5jAWVqnKCyF",
    "192.168.100.41": "iHwkL4PhJOMVKKQPMQ7b",
    "192.168.100.44": "mLGRKx0dqgReSowDM7ar",
    "192.168.100.42": "qFeuwgcmJEXmeI82PohW",
    "192.168.100.43": "pkqYx7oXBbjHdhZCJFlv",
    "192.168.100.49": "1NITBBX4tqX3dEFjyAnZ",
    "192.168.100.45": "Xy416AUJ1xRTLh66jc8m",
    "192.168.100.47": "cwOoYS0V1GkCMbzGMawz",
    "192.168.100.46": "KK4ocD3DV7HXyOgZHjne",
    "192.168.100.50": "L7W84Q2uPVCHpl26E130",
    "192.168.100.48": "QfG9iLzUMpuql82CNiC8",
    "192.168.100.51": "UPMkkrf8wpdfRB7u2lPD",
    "192.168.100.62": "AYiTyD0L9be0uknhsRuk",
    "192.168.100.58": "irpAhCRzmjqXNFvhRBgh",
    "192.168.100.52": "pU9CNRRGeC2BeY9ihvTj",
    "192.168.100.53": "tPbDwplAxqhR8uAfaQen",
    "192.168.100.55": "8lp3cloZqyeS2C3Ta1T1",
    "192.168.100.57": "5OoJLpVqI3XeXJqYP5J2",
    "192.168.100.59": "uAqfcXL6KUiDe3nZRhHD",
    "192.168.100.60": "02POibXHaoodE4UXjUHK",
    "192.168.100.56": "jamF5tUfKQA496lybQaW",
    "192.168.100.15": "CXeY3rph19sCtrQ3Wc1j",
    "192.168.100.16": "TzlMm078GyDw7phof1rE",
    "192.168.100.34": "WozFxiIh8jNM0xUKAtNW",
    "192.168.100.64": "JCSP8GDTzInFuZMj1ihz",
    "192.168.100.65": "5W1MWAFSZhkH4MYT4xrS",
    "192.168.100.23": "8JXlAhaUZ4L9MFrPZzu3",
    "192.168.100.66": "orLac2h34tImmdf2s1oM",
    "192.168.100.10": "Ef4jB5noK80FDAvrr5Mt",
    "192.168.100.61": "f0OsbBbQx1gzuQ4FkEBp",
    "192.168.100.12": "7NEy7UWINFxFZi0Qx0wd",
}

iglist = ["192.168.100.5"]
#------------------------------------------------
def get_ip_nametoken(attribute_data):
    global gwtoken
    for attr in attribute_data:
        if attr["key"] == "ip_address":
            ip_name = attr["value"]
            return gwtoken[ip_name] 



def creat_mqtt_configuration(config):
    atomq = AutoUpdateMqtt()
    return atomq.get_mqttjson(config)

def update_shared_attr(key, value,dev_id):
    # 调用另一个 API
    shared_scope_url = f"{base_telemetry_url}{dev_id}/SHARED_SCOPE"
    temp = None
    shared_scope_payload = {key: value}
    shared_scope_response = requests.post(shared_scope_url, headers=headers, json=shared_scope_payload)

    if shared_scope_response.status_code == 200:
        print(f"Successfully called SHARED_SCOPE API for device {dev_id}")
    else:
        print(f"Failed to call SHARED_SCOPE API for device {dev_id}. Status code: {shared_scope_response.status_code}")

        
# 登录获取token
login_url = "http://om.jujiembs.com/api/auth/login"
login_payload = {
    "username": "ckrmyy@jj.com",
    "password": "1812d898"
}

login_response = requests.post(login_url, json=login_payload)
login_data = login_response.json()
token = login_data.get('token')

if not token:
    print("Login failed. No token obtained.")
    exit(1)

# 获取设备列表
# device_list_url = "http://om.jujiembs.com/api/tenant/deviceInfos"
# headers = {'X-Authorization': f'Bearer {token}'}
# params = {'pageSize': 10, 'page': 0, 'sortProperty': 'createdTime', 'sortOrder': 'DESC'}

# device_list_response = requests.get(device_list_url, headers=headers, params=params)
# device_list_data = device_list_response.json()

cus_url="http://om.jujiembs.com/api/auth/user"
headers = {'X-Authorization': f'Bearer {token}'}
value = requests.get(cus_url, headers=headers)
if value.status_code == 200:
    value = json.loads(value.content.decode("utf-8") )

id = value["customerId"]["id"]

#客户api
# id = None
device_list_url = f"http://om.jujiembs.com/api/customer/{id}/deviceInfos"
headers = {'X-Authorization': f'Bearer {token}'}
params = {'pageSize': 10, 'page': 0, 'sortProperty': 'createdTime', 'sortOrder': 'DESC'}

value = requests.get(device_list_url, headers=headers,params = params)
# 处理设备列表数据
if value.status_code == 200:
    device_list_data = json.loads(value.content.decode("utf-8") )

total_pages = device_list_data.get('totalPages', 0)
device_ids = []

for page in range(total_pages):
    params['page'] = page
    device_list_response = requests.get(device_list_url, headers=headers, params=params)
    device_list_data = device_list_response.json()
    devices = device_list_data.get('data', [])
    for device in devices:
        device_id = device.get('id')
        if device_id:
            device_ids.append(device_id["id"])

# 遍历设备并调用 API
for device_id in device_ids:
    try:
        # 获取设备属性
        attribute_url = f"{base_telemetry_url}{device_id}/values/attributes"
        attribute_response = requests.get(attribute_url, headers=headers)
        attribute_data = attribute_response.json()
        devicetoken = get_ip_nametoken(attribute_data)

        for attr in attribute_data:
            for a in attribute_data:
                if attr["key"] == "ip_address":
                    ip_name = attr["value"]
                    if ip_name in iglist:
                        continue
            if attr["key"] == "thingsboard-gateway_config":
                if attr["value"] != "none":
                    if attr["value"]["thingsboard"]["host"] != "om.jujiembs.com":
                        #{"host":"om.jujiembs.com"}
                        update_shared_attr("thingsboard-gateway", {"host":"om.jujiembs.com"},device_id)
                    if attr["value"]["thingsboard"]["security"]["accessToken"] == "aaaaaaaaaa":
                        #{"host":"om.jujiembs.com"}

                        update_shared_attr("thingsboard-gateway", {"token":devicetoken},device_id)
            #更新mqtt.json
            if attr["key"] == "zigbee2mqtt_config":
                mqcof = creat_mqtt_configuration(attr["value"])
                if type(mqcof) == dict:
                    update_shared_attr("thingsboard-gateway", {"mqtt_json":mqcof},device_id)
    except Exception as e:
        print("Error creating:%s", e)
        print(attribute_data)
        continue
    

    # 获取遥测值
    timeseries_url = f"{base_telemetry_url}{device_id}/values/timeseries"
    timeseries_response = requests.get(timeseries_url, headers=headers)
    timeseries_data = timeseries_response.json()
    

# 遍历设备并调用 API
for device_id in device_ids:
    update_shared_attr("cmd", "get_curr_data", device_id)
    # 获取设备属性
    attribute_url = f"{base_telemetry_url}{device_id}/values/attributes"
    attribute_response = requests.get(attribute_url, headers=headers)
    attribute_data = attribute_response.json()

# 获取遥测值
    timeseries_url = f"{base_telemetry_url}{device_id}/values/timeseries"
    timeseries_response = requests.get(timeseries_url, headers=headers)
    timeseries_data = timeseries_response.json()
    #调用api写入token
    # 创建设备文件夹
    device_folder = os.path.join('device_data', f"device_{device_id}")
    os.makedirs(device_folder, exist_ok=True)

    # 存储数据到设备文件夹
    with open(os.path.join(device_folder, 'attributes.json'), 'w') as attribute_file:
        json.dump(attribute_data, attribute_file)

    with open(os.path.join(device_folder, 'timeseries.json'), 'w') as timeseries_file:
        json.dump(timeseries_data, timeseries_file)



print("Data has been successfully collected and saved to individual device folders.")
